<template>
  <view class="login-status-container">
    <!-- 判断用户是否已登录 -->
    <view v-if="isLoggedIn">
      <!-- 登录后的聊天室页面 -->
      <view class="chat-container">
        <view class="chat-header">
          <text class="chat-title">聊天室</text><P></P>

          <text class="online-count">在线人数: {{ onlineCount }}</text>
        </view>

		  <text style="font-size: 14px;">这个聊天室根据缘分匹配，显示真实的在线人数，并通过特定时间段将合适的人聚集在一起。</text>
        <view class="chat-messages" ref="chatMessages">
          <!-- 消息展示 -->
          <view v-for="(message, index) in messages" :key="index" :class="['message-item', { 'my-message': message.username === username }]">
            <text class="message-username">{{ message.username }}:</text>
			
            <text class="message-content">{{ message.content }}</text>
          </view>
        </view>

        <view class="chat-input-container">
          <input 
            v-model="newMessage" 
            @keyup.enter="sendMessage" 
            placeholder="输入消息..." 
            class="chat-input" 
            ref="input"
          />
          <button @click="sendMessage" class="send-button">发送</button>
        </view>

        <button @click="logout" class="logout-btn">退出登录</button>
      </view>
    </view>

    <!-- 未登录 -->
    <view v-else>
      <view class="not-logged-in">
         <text 
            class="login-prompt" 
            @click="goToLogin"
            style="cursor: pointer; padding: 12px 20px; background-color: #4CAF50; color: #fff; border-radius: 15px; font-size: 16px; transition: background-color 0.3s, transform 0.3s;">
            请登录后进行交友
          </text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      onlineCount: 0,
      isLoggedIn: false,
      newMessage: '',
      messages: [],
      socket: null,
    };
  },
  methods: {
    // 设置 WebSocket 连接
    setupSocket() {
      this.socket = new WebSocket('ws://localhost:3000');  // 连接到 WebSocket 服务器

      this.socket.onopen = () => {
        console.log('WebSocket连接已打开');
      };

      this.socket.onmessage = (event) => {
        const message = JSON.parse(event.data);
        if (message.type === 'online') {
          this.onlineCount = message.count;
        } else {
          this.messages.push(message);  // 接收到消息并添加到消息列表
          this.$nextTick(() => {
            // 滚动到消息列表的底部
            this.scrollToBottom();
          });
        }
      };

      this.socket.onerror = (error) => {
        console.error('WebSocket 错误:', error);
      };

      this.socket.onclose = () => {
        console.log('WebSocket 连接关闭');
      };
    },

    // 发送消息
    sendMessage() {
      if (this.newMessage.trim() === '') return;

      const message = {
        username: this.username,
        content: this.newMessage,
        type: 'text',
      };
      this.messages.push(message);  // 将消息添加到自己的消息列表
      this.socket.send(JSON.stringify(message));  // 发送消息到服务器
      this.newMessage = '';  // 清空输入框

      // 滚动到消息列表的底部
      this.$nextTick(() => {
        this.scrollToBottom();
        // 发送后光标聚焦
        this.$refs.input.focus();
      });
    },

    // 滚动到最新消息
    scrollToBottom() {
      const chatMessages = this.$refs.chatMessages;
      chatMessages.scrollTop = chatMessages.scrollHeight;
    },

    // 退出登录
    logout() {
      uni.removeStorageSync('token');
      uni.removeStorageSync('username');
      this.isLoggedIn = false;
      if (this.socket) {
        this.socket.close();
      }
    },

    // 跳转到登录页面
    goToLogin() {
      uni.switchTab({
        url: '/pages/mine/mine',  // 使用 switchTab 跳转到 mine 页面
      });
    }
  },
  mounted() {
    const storedUsername = uni.getStorageSync('username');
    this.username = storedUsername || '';
    this.isLoggedIn = !!storedUsername;
    if (this.isLoggedIn) {
      this.setupSocket();
    }
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close();
    }
  }
};
</script>

<style scoped>
/* 主要容器样式 */
.login-status-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f0f2f5; /* 淡灰色背景 */
  padding: 20px;
  justify-content: center;
  align-items: center;
}

/* 聊天容器样式 */
.chat-container {
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.1); /* 更精致的阴影 */
  border-radius: 16px;
  width: 100%;
  max-width: 640px; /* 最大宽度 */
  height: 80vh; /* 固定容积 */
  transition: transform 0.3s ease-in-out;
}

.chat-container:hover {
  transform: scale(1.03); /* 鼠标悬停时放大 */
}

/* 聊天头部 */
.chat-header {
  background-color: #007bff;
  color: white;
  padding: 18px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
  font-size: 20px;
  font-weight: 700;
}

/* 在线人数 */
.online-count {
  font-size: 14px;
  font-weight: 500;
}

/* 消息展示区域 */
.chat-messages {
  overflow-y: auto;
  flex-grow: 1;
  padding: 20px;
  background-color: #fafafa; /* 更清新的背景色 */
  border-bottom: 1px solid #ddd;
}

/* 消息样式 */
.message-item {
  margin-bottom: 12px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.my-message {
  align-items: flex-end;
}

.message-username {
  font-weight: bold;
  color: #333;
  font-size: 14px;
}

.message-content {
  font-size: 16px;
  color: #555;
  word-break: break-word;
  line-height: 1.6;
  padding: 12px;
  border-radius: 12px;
  background-color: #e1e8f0; /* 消息气泡颜色 */
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 输入框区域 */
.chat-input-container {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  background-color: #ffffff;
  border-top: 1px solid #ddd;
}

.chat-input {
  flex-grow: 1;
  padding: 12px 20px;
  border-radius: 30px;
  border: 1px solid #ddd;
  font-size: 16px;
  outline: none;
  box-shadow: inset 0 2px 6px rgba(0, 0, 0, 0.1);
}

.chat-input:focus {
  border-color: #007bff;
}

/* 按钮样式 */
.send-button {
  padding: 12px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.send-button:hover {
  background-color: #0056b3;
}

.logout-btn {
  background-color: #dc3545;
  color: white;
  padding: 12px;
  margin-top: 20px;
  border-radius: 20px;
  text-align: center;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.logout-btn:hover {
  background-color: #c82333;
}

/* 未登录提示 */
.not-logged-in {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
}

.login-prompt {
  font-size: 18px;
  color: #007bff;
  cursor: pointer;
}

.login-prompt:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    margin: 0;
    border-radius: 12px;
  }

  .chat-header {
    font-size: 16px;
    padding: 12px 18px;
  }

  .message-content {
    font-size: 14px;
  }

  .chat-input-container {
    padding: 10px;
  }

  .chat-input {
    font-size: 14px;
    padding: 10px 16px;
  }

  .send-button {
    font-size: 14px;
    padding: 10px 16px;
  }

  .logout-btn {
    font-size: 14px;
    padding: 10px;
  }
}
</style>
